from flask_login import UserMixin
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from app.utils.db import Base
from datetime import datetime

class User(UserMixin, Base):
    """
    用户模型
    """
    __tablename__ = 'users'
    
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)
    email = Column(String(50))
    password = Column(String(255), nullable=False)
    description = Column(String(100))
    is_admin = Column(Boolean, default=False) # 是否为管理员
    is_active = Column(Integer, default=0)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime)
    
    @property
    def username(self):
        return self.name
    
    def get_id(self):
        return str(self.id)
    
    @property
    def is_active(self):
        return True
    
    @property
    def is_anonymous(self):
        return False
    
    @property
    def is_authenticated(self):
        return True
    
    def __repr__(self):
        return f"<User(id={self.id}, name={self.name})>"
    
    def to_dict(self):
        """
        将对象转换为字典，方便JSON序列化
        """
        return {
            "id": self.id,
            "name": self.name,
            "email": self.email,
            "description": self.description,
            "is_admin": self.is_admin,
            "is_active": self.is_active,
            "created_at": self.created_at.strftime("%Y-%m-%d %H:%M:%S") if self.created_at else None,
            "updated_at": self.updated_at.strftime("%Y-%m-%d %H:%M:%S") if self.updated_at else None
        } 